<?php
/**
 * Created by PhpStorm.
 * User: fengzi
 * Date: 2019/4/1
 * Time: 15:02
 */

namespace app\admin\logic;
use app\admin\logic\code\ErrorCode;
use app\common\model\Operation;
use app\common\model\Role;
use think\facade\Cache;

class OperationLogic extends BaseLogic {

    private $operationModel;

    public function __construct()
    {
        $this->operationModel = new Operation();
    }

    /**
     * 获取首页列表
     * @param int $nowPage
     * @return mixed
     */
    public function menuList($tempWhere, $nowPage = 1){
        if ($tempWhere['type']){
            $where[] = ['type', '=', $tempWhere['type']];
        }
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', '=', $tempWhere['status']];
        }
        if ($tempWhere['name']){
            $where[] = ['name', 'like', "%".$tempWhere['name']."%"];
        }

        $count = $this->operationModel->where($where)->count();
        $list = $this->operationModel->where($where)->page($nowPage, self::$pageNum)->select();
        if ($count > 0){
            foreach ($list as $key=>$val){
                $list[$key]->type_text = $val->type_text;
            }
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $list, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    //获取详情
    public function info($id){
        $info = $this->operationModel->get($id, 'child');
        if ($info){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $info);
        } else{
            return ajaxArr(ErrorCode::$INFONULL, '详情信息为空');
        }
    }

    //获取父级
    public function getParentMenu(){
        $where['status'] = 1;
        $where['is_menu'] = 1;
        $where['pid'] = 0;
        $list = Operation::field('id,name')->where($where)->select();
        return $list;
    }

    /**
     * 菜单操作
     * @param $data
     * @return mixed
     */
    public function handle($data){
        $validate = new \app\admin\validate\Operation();
        $act = $data['act'];
        unset($data['act']);
        if ($act == 'add' || $act == 'edit'){
            //编辑/添加操作过滤字段
            if (!$validate->check($data)) {
                return ajaxArr(ErrorCode::$PARAMVALIDATE, $validate->getError());
            }
        }
        $res = false;
        switch ($act){
            case 'add':
                $res = $this->operationModel->allowField(true)->save($_POST);
                break;
            case 'edit':
                break;
            case 'del':
                $operation = $this->operationModel->get($data['id']);
                $res = $operation->delete();
                break;
            case 'batch_del':
                //批量删除
                $res = $this->operationModel->destroy($data['ids']);
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    /**
     * 查找子菜单列表
     * @param $pId
     */
    public function getChildMenu($pId, $type=0){
        $where['pid'] = $pId;
        $where['status'] = 1;
        $where['is_menu'] = 1;
        if ($type >0){
            $where['type'] = $type;
        }
        $menuList = $this->operationModel->field('id,name')->where($where)->select();
        if (count($menuList) > 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $menuList);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }


    /**
     * 获取全部菜单列表
     * @return mixed
     */
    public function getAllMenu($isMenu = 1, $isAll = false){
        $adminMenu = Cache::get('admin_menu');
        if ($adminMenu && !$isAll){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $adminMenu);
        } else{
            if ($isAll){
                if ($isMenu){
                    $where['is_menu'] = 1;
                }
                $where['status'] = 1;
                $list = $this->operationModel->where($where)->field('id,name,pid,action_url,icon')->order('sort desc')->select();
                $list = json_decode(json_encode($list), true);
                $menuList = getTree($list, 0);
                return ajaxArr(ErrorCode::$SUCCESS, 'success', $menuList);
            } else{
                $roleModel = new Role();
                $oWhere[] = ['o.status', '=', 1];
                $oWhere[] = ['o.type', '=', 1];
                $list = $roleModel->alias('r')->field('ro.role_id,o.name,o.action_url,o.icon,o.pid,o.id,o.is_menu')->
                                leftJoin('role_operation ro', 'r.id = ro.role_id')->
                                leftJoin('operation o', 'o.id = ro.operation_id')->
                                where($oWhere)
                                ->select();
                $temp = [];
                $roleOperation = [];
                foreach ($list as $key=>$val){
                    if ($val->is_menu){
                        $temp[$val['role_id']][] = json_decode(json_encode($val), true);
                    }
                    $roleOperation[$val['role_id']][] = $val->action_url;
                }
                Cache::set('role_operation', $roleOperation);
                $menuTemp = [];
                foreach ($temp as $key=>$val){
                    $menuTemp[$key]['menu_tree'] = getTree($val, 0);
                }
                //管理员全菜单
                $allWhere['is_menu'] = 1;
                $allWhere['status'] = 1;
                $allWhere['type'] = 1;
                $allMenu = $this->operationModel->where($allWhere)->field('id,name,pid,action_url,icon')->order('sort desc')->select();
                $allMenu = json_decode(json_encode($allMenu), true);
                $allMenuTree = getTree($allMenu, 0);
                $menuTemp[0]['menu_tree'] = $allMenuTree;
                Cache::set('admin_menu', $menuTemp);
                return ajaxArr(ErrorCode::$SUCCESS, 'success', $menuTemp);
            }
        }
    }

}